package org.example.service.impl;

import org.example.MyExecption.BusinessException;
import org.example.domain.File;
import org.example.mapper.UploadMapper;
import org.example.myEnum.ErrorCode;
import org.example.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.url}")
    private String uploadUrl;

    @Autowired
    private UploadMapper uploadMapper;
    /***
     * 文件上传
     * @param imageFile
     * @return
     */
    @Override
    public String upload(MultipartFile imageFile) {
        if (imageFile == null || imageFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "上传文件不能为空");
        }
        
        // 处理图片上传
        String fileUrl = uploadImage(imageFile);
        
        // 创建文件记录
        File file = new File();
        file.setId(UUID.randomUUID().toString());
        file.setFileName(imageFile.getOriginalFilename());
        file.setPath(fileUrl);
        file.setStatus("unbind"); // 未绑定业务id
        file.setCreateTime(new Date());
        
        // 设置过期时间为当前时间加24小时
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR_OF_DAY, 24);
        file.setExpireTime(calendar.getTime());
        
        // 保存文件记录到数据库
        int result = uploadMapper.insert(file);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "文件记录保存失败");
        }
        
        return file.getId();
    }

    private String uploadImage(MultipartFile file) {
        // 确保上传目录存在
        java.io.File uploadDir = new java.io.File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;

        // 保存文件
        java.io.File destFile = new java.io.File(uploadPath + java.io.File.separator + filename);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "图片上传失败: " + e.getMessage());
        }

        // 返回可访问的URL
        return uploadUrl + "/" + filename;
    }
}
